<template>
	<view>
		<map style="width: 100vw; height: 100vh" v-show="show" :show-location="true" :latitude="latitude" id="map" ref="map" 
			:longitude="longitude" scale="14" :polyline="polyline" @regionchange="regionchange" :enable-satellite="true" @callouttap="callouttap"
			@markertap="markertap" :markers="markers">
		</map>
	</view>
</template>

<script>
	import all from '../../../static/zhuan2.js'
	export default {
		name: "liwu",
		data() {
			return {
				title: 'Hello',
				show: true,
				luxian: "",
				polyline: [],
				latitude: "37.518250",
				longitude: "121.431709",
				markersdk: [],
				markers: [],
				sear: {
					user_id: JSON.parse(uni.getStorageSync('person')).id, //	是	int	当前登录的用户id
					focus_id: "", //	是	int	关注人的报名id
					game_id: uni.getStorageSync('activity_id'), //	是	int	赛事id
					package_id:uni.getStorageSync('pack_id'),
					is_my_focus:0
				},
				scale:14,
				map:"",
				list:[],
				zhikanguanzhu:false,
			}
		},
		onLoad() {

		},
		onShow() {

		},
		mounted() {
			
			this.$bus.$on('dingweidao',item => {
			  this.quzhongxin(item)
			})
			this.map = uni.createMapContext("map", this);
			console.log(this.map)
			
			// this.map.getRegion({
			// 	complete(res) {
			// 	  console.log('getRegion', res)
			// 	}
			// })
			
			// this.map.initMarkerCluster({
			// 	enableDefaultStyle: true,
			// 	zoomOnClick: true,
			// 	gridSize: 60,
			// 	complete(res) {
			// 	  console.log('initMarkerCluster', res)
			// 	}
			// });
			
			// this.map.on("markerClusterCreate", (e) => {
			// 	console.log("markerClusterCreate", e);
			// });
			
			
			Promise.all([this.getluxian()]).then((res) => {
				// this.getren();
			})
			// setInterval(() => {
			// 	this.getren();
			// }, 10000)
		},
		methods: {
			
			//查找人过来区重点
			quzhongxin:function(item){
				this.markers.forEach(item2=>{
					if(item2.id == item.id){
						console.log(item2)
						this.latitude = item2.latitude
						this.longitude = item2.longitude
						
						this.map.moveToLocation({
									longitude: this.longitude,
									latitude: this.latitude
						});
					}
				})
				
			},
			zhiguanzhuma:function(){
				if(this.sear.is_my_focus == 0){
					this.sear.is_my_focus = 1
				}else{
					this.sear.is_my_focus = 0
				}
				this.getren()
			},
			regionchange:function(e){
				
				this.scale = e.detail.scale

				if(this.scale > 15){
					this.map.pageVm.markers.forEach(item=>{
						if(item.name){
							item.iconPath = item.head_img
						}
					})
				}else{
					this.map.pageVm.markers.forEach(item=>{
						if(item.name){
							item.iconPath = 'https://cdn.rockysports.cn/h5zhibo/hh5.png'
						}
					})
				}
				
				
				this.map.addGroundOverlay({
					id:54321,//	String		是	图片图层 id
					src:"http://store.91haoka.cn/upload/pic/16668607321521507965.jpg",//	String		是	图片路径，支持网络图片、临时路径、代码包路径
					bounds:{
						southwest:{
							longitude:"116.272038",
							latitude:"39.845613"
						},
						northeast:{
							longitude:"116.272038",
							latitude:"39.845613"
						},
					},//	Object		是	图片覆盖的经纬度范围
					visible:true,//	Boolean	true	否	是否可见
					zIndex:1,//	Number	1	否	图层绘制顺序
					opacity:1,//	Number	1	否	图层透明度
					success(res){
						console.log(res)
					},//	function		否	接口调用成功的回调函数
					fail(res){
						console.log(res)
					},//	function		否	接口调用失败的回调函数
					complete(){
						console.log(res)
					},//	function		否	接口调用结束的回调函数（调用成功、失败都会执行）
				})
			},
			// getScale:function(e){
			// 	console.log(e)
			// },
			bearing(start, end) {
				let rad = Math.PI / 180,
					lat1 = start.latitude * rad,
					lat2 = end.latitude * rad,
					lon1 = start.longitude * rad,
					lon2 = end.longitude * rad;
				const a = Math.sin(lon2 - lon1) * Math.cos(lat2);
				const b = Math.cos(lat1) * Math.sin(lat2) -
					Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1);
				return this.radiansToDegrees(Math.atan2(a, b));
			},

			radiansToDegrees(radians) {
				const degrees = radians % (2 * Math.PI);
				return degrees * 180 / Math.PI;
			},

			callouttap: function(e) {
				if (!e.detail.markerId.includes('dakadian')) {
					this.$emit('dianren', e.detail.markerId)
				}

			},
			markertap: function(e) {
				console.log(e)

				this.list.forEach(item=>{
					if(item.id == e.detail.markerId){
						this.$emit('dianren', e.detail.markerId)
					}
				})
			},
			getluxian: function() {
				return new Promise((ress, rej) => {
					uni.$u.http.get(this.urlass + '/api/sport/api/position/package/list5', {
						params: {
							game_id: uni.getStorageSync('activity_id')
						}
					}).then(res => {
						if (res.data.msg.code == 0) {
							this.luxian = res.data.data
							
							
							this.$emit('getzubie', this.luxian)
							// if(this.luxian[0].data){
							// 	let luxian = JSON.parse(this.luxian[0].data).luxian
							// 	let x = all.wgs84togcj02(luxian[0][0], luxian[0][1])
							// 	this.longitude = parseFloat(x[0])
							// 	this.latitude = parseFloat(x[1])
							// }else{
							// 	this.latitude = "37.518250"
							// 	this.longitude = "121.431709"
							//}
							this.show = true
							if (this.luxian != '') {
								
								if(!uni.getStorageSync('pack_id')){
									uni.setStorageSync('pack_id', this.luxian[0].id)
								}else{
									this.luxian.forEach(item=>{
										if(item.id == uni.getStorageSync('pack_id')){
											this.$emit('jinlaiyouzubie', item)
										}
									})
									
								}
								
								
								
								this.luxian.forEach((item, index) => {
									//指定组别
									
									if (item.data != '' && item.id == uni.getStorageSync('pack_id')) {
									// if (item.data != '') {
										
										let p =  new Promise((ress, rej) => {
											uni.$u.http.get(item.luxianurl).then(res => {
												ress(res)
												})
											})
										p.then(res=>{
										
											this.polyline = []
											this.markersdk = []
											
											
											let luxian = res.data.luxian
											let xx = all.wgs84togcj02(luxian[0][0], luxian[0][1])
											
											this.longitude = parseFloat(xx[0])
											this.latitude = parseFloat(xx[1])
											
											let arr = []
											luxian.forEach((item2, index2) => {
											
												if (item2[0] && item2[1]) {
													let x = all.wgs84togcj02(item2[0],item2[1])
													arr.push({
														longitude: parseFloat(x[0]),
														latitude: parseFloat(x[1])
													})
											
													//话箭头
													if (index2 % 75 == 0) {
														if (luxian[index2 + 1]) {
															let x1 = all.wgs84togcj02(item2[0],item2[1])
											
															let x2 = all.wgs84togcj02(luxian[index2 + 1][0],luxian[index2 + 1][1])
											
															let start = {
																longitude: parseFloat(x1[0]),
																latitude: parseFloat(x1[1])
															}
															let end = {
																longitude: parseFloat(x2[0]),
																latitude: parseFloat(x2[1])
															}
											
															let du = this.bearing(start,end)
											
															let obj2 = {
																id: 'jiantou' + index + index2,
																latitude: parseFloat(x1[1]),
																longitude: parseFloat(x1[0]),
																iconPath: "https://cdn.rockysports.cn/h5zhibo/baijiantou.png",
																width: "10",
																height: "10",
																rotate: du,
																alpha: '0.3'
															}
															this.markersdk.push(obj2)
														}
											
													}
												}
											})
											let obj = {
												points: arr,
												color: '#316FFF',
												width: 5
											}
											this.polyline.push(obj)
											
											let dakadian = res.data.dakadian
											
											
											dakadian.forEach((item2, index2) => {
												if (item2.name.includes('[')) {
													item2.name = item2.name.slice(9, -3)
												}
												let width = 25
												let height = 25
												let content = item2.name
												let iconPath =
													"https://cdn.rockysports.cn/biaoji1.png"
												//cp点图
												if (item2.name.includes('Cp') || item2.name.includes('CP')) {
													iconPath =
														'https://cdn.rockysports.cn/h5zhibo/hh1.png'
												}
												//sp图
												if (item2.name.includes('Sp') || item2.name.includes('SP')) {
													iconPath =
														'https://cdn.rockysports.cn/h5zhibo/hh3.png'
												}
												//jp图
												if (item2.name.includes('JS') || item2.name.includes('Js')) {
													iconPath =
														'https://cdn.rockysports.cn/h5zhibo/hh6.png'
												}
												
												if (item2.name.includes('起点')) {
													iconPath =
														'https://cdn.rockysports.cn/h5zhibo/hh9.png'
													width = 110
													height = 60
													content = ''
												}
												if (item2.name.includes('终点')) {
													iconPath =
														'https://cdn.rockysports.cn/h5zhibo/hh7.png'
													width = 110
													height = 60
													content = ''
												}
												if (item2.name.includes('起终点')) {
													iconPath =
														'https://cdn.rockysports.cn/h5zhibo/hh8.png'
													width = 110
													height = 60
													content = ''
												}
											
												let x = all.wgs84togcj02(parseFloat(item2.zuobiao[0]), parseFloat(item2.zuobiao[1]))
											
												let obj = {
													id: 'dakadian' + index2,
													latitude: parseFloat(x[1]),
													longitude: parseFloat(x[0]),
													iconPath: iconPath,
													width: width,
													height: height,
													joinCluster: true,
													callout: {
														content: content,
														color: '#fff',
														fontSize: 12,
														borderRadius: 1,
														borderWidth: 0,
														borderColor: 'rgba(255,255,255,0)',
														bgColor: 'rgba(0,0,0,0.2)',
														padding: 5,
														display: 'ALWAYS'
													}
												}
												
												//公里数
												if (item2.name.includes('km')) {
													item2.name = item2.name.replace(new RegExp('km','g'),"")
													if(parseInt(item2.name)  < 10){
														item2.name = '0' + item2.name
													}
													obj = {
														id: 'dakadian' + index2,
														latitude: parseFloat(x[1]),
														longitude: parseFloat(x[0]),
														width: "0",
														height: "0",
														iconPath: 'https://cdn.rockysports.cn/h5zhibo/hh2.png',
														
														label: {
															content: item2.name,
															color: '#fff',
															fontSize: 12,
															textAlign:'center',
															borderRadius: 26,
															borderWidth: 3,
															borderColor: 'rgba(255,255,255,1)',
															bgColor: 'rgba(0, 33, 205, 1)',
															padding: 5,
															display: 'ALWAYS',
															x:-15,
															y:-29
														}
													}
													this.markersdk.push(obj)
												}else{
													
												}
												
												
												
												this.markers = [...this.list,...this.markersdk]
											})
										})
										
										

									}else{
										
									}
									ress()
								})
							}
						}
					})
				})

			},
			//获取url的code用
			getUrlParam: function(name) {
				var query = window.location.search.substring(1);
				var vars = query.split("&");
				for (var i = 0; i < vars.length; i++) {
					var pair = vars[i].split("=");
					if (pair[0] == name) {
						return pair[1];
					}
				}
				return (false);
			},


			xiangxin: function(player_id, index) {
				axios.get(this.urlass + '/api/sport/admin/result?player_id=' + player_id)
					.then((response) => {

						if (index) {
							this.zhongxin(this.ren[index].longitude, this.ren[index].latitude)
						}



						if (localStorage.getItem('guanzhu') != null) {
							this.guanzhuids = localStorage.getItem('guanzhu').split(',')
						}
						let id = (response.data.data.player.sign_id).toString()
						// console.log(this.guanzhuids,player_id,player_id.toString())
						if (this.guanzhuids.includes(id)) {
							this.$set(response.data.data, 'guanzhu', true)
						}
						this.person = response.data.data

						this.searchshow = false
						this.grenxinxi = true
						// for(let i in response.data.data){
						// 	let id = response.data.data[i].order_id
						// 	if(this.guanzhuids.includes(id.toString())){
						// 		this.$set(response.data.data[i],'guanzhu',true)
						// 	}
						// }
					})

			},
			sousuogo: function() {
				this.getren()
			},

			zhongxin: function(x, y) {
				this.map.centerAndZoom(new T.LngLat(x, y), 18);
			},
			shuaxin: async function() {
				await this.getren()
				this.map.clearOverLays();
				this.saidao()
				this.huodecanshu()

			},
			//获取人的位置
			getren() {
				uni.$u.http.post(this.urlass + '/api/position/position/liveuserpos', this.sear).then(res => {
					let list = []
					res.data.data.data.forEach(item => {
						
						if (item.longitude && item.latitude) {

							item.longitude = parseFloat(item.longitude)
							item.latitude = parseFloat(item.latitude)
							
							if(this.scale > 15){
								this.$set(item, 'iconPath', item.head_img)
							}else{
								this.$set(item, 'iconPath', 'https://cdn.rockysports.cn/h5zhibo/hh5.png')
							}
							
							this.$set(item, 'width', 30)
							this.$set(item, 'height', 30)
							this.$set(item, 'joinCluster', true)
							this.$set(item, 'callout', {
								content: item.name,
								color: '#fff',
								fontSize: 12,
								borderRadius: 1,
								borderWidth: 0,
								borderColor: 'rgba(255,255,255,0)',
								bgColor: 'rgba(0,0,0,0.2)',
								padding: 5,
								display: 'ALWAYS'
							})
							
							list.push(item)
						}
					})
					this.list = list
					this.markers = [...list, ...this.markersdk]
					//console.log(this.markers)
				})
			}
		},
	}
</script>

<style scoped lang="scss">
	/deep/ .csssprite{ border-radius: 30rpx;}
	.content {
		/deep/ .u-popup__content {
			background: #fff;
			padding: 35rpx;
			color: #333;
		}
		
		.gz {
			background: #F6F6F6;
			padding: 0rpx 20rpx;
			height: 60rpx;
			line-height: 60rpx;
			border-radius: 30rpx;
		}
	}
</style>
